<?php
/**
 * Create a new Inquiry
 */

use Fox\SalesDistribution\Sales\Inquiry\Messages;
use Fox\SalesDistribution\Sales;
use Fox\Dao\SqlFragment;
use Fox\Message;
use Fox\SalesDistribution\Sales\Inquiry\Text;
use Fox\Generator;
use Fox\Html\Wrapper;
use Fox\Html\TabPanel;
use Fox\Html\TabPanel\Tab;
use Fox\SalesDistribution\Sales\Partner\Role;
use Fox\SalesDistribution\Sales\Inquiry\Partner;
use Fox\Common\Customer,Fox\SalesDistribution\Sales\Inquiry;
use Fox\Html\Screen;

$id = Xview::instance()->val("inquiryid");

try {
	$partnersToDelete = array();
	$inquiry = new Inquiry($id);
	$data = $inquiry->getData();
	$root = $inquiry->itemTree();
	$items = $inquiry->items();
	$data['gCompetitors'] = array();
	// Retrieve Cancel If it does not exist it will be left as blank
	$data['cancel_reason'] = $inquiry->texts(Text::ID_CANCEL_REASON)->content();
	$status = Xview::instance()->val("status",$data['status']);

	foreach($inquiry->partners() as $partner)
	{
		switch ($partner->role)
		{
			case Role::SOLD_TO_PARTY :
				$billData = $partner->customer()->getData();
				$address =  $partner->customer()->address()->getData();
				$data['customerid'] = $partner->customer()->getId();
				$data['customername'] = $billData['name1'];

				$data['street'] = empty($data['street'])? $address['street'] : $data['street'];
				$data['postal_code'] = empty($data['postal_code'])? $address['postal_code'] : $data['postal_code'];
				$data['city'] = empty($data['city'])? $address['city'] : $data['city'];
				$data['phone1'] = empty($data['phone1'])? $address['phone1'] : $data['phone1'];
				$data['email1'] = empty($data['email1'])? $address['email1'] : $data['email1'];
				$data['function'] = empty($data['function'])? $billData['function'] : $data['function'];
			break;

			case Role::CONTACT_PERSON :
				$contactData = $partner->customer()->getData();
				$address =  $partner->customer()->address()->getData();
				$data['contactid'] = $partner->customer()->getId();
				$data['contact'] = $contactData['name1'];
				if(!empty($address['street']))
					$data['street'] = $address['street'];
				if(!empty($address['postal_code']))
					$data['postal_code'] = $address['postal_code'];
				if(!empty($address['city']))
					$data['city'] = $address['city'];
				if(!empty($address['phone1']))
					$data['phone1'] = $address['phone1'];
				if(!empty($address['email1']))
					$data['email1'] = $address['email1'];
				if(!empty($contactData['function']))
					$data['function'] = $contactData['function'];
				break;
			case Role::RESPONSIBLE_AGENCY :
				$data['agency'] = $partner->partnerid();
			break;

			case Role::RESPONSIBLE_PERSON :
				$data['sourceid'] = $partner->partnerid();
			break;

			case Role::OPERATIONAL_ENTITY :
				$partnersToDelete[$partner->salesId()] = $partner;
				$data['op_entity'][$partner->partnerid()] = true;

			break;

			case Role::SUCCESSFUL_BIDER :
				$data['winnerid'] = $partner->partnerid();
			break;

			case Role::COMPETITOR :
				$partnersToDelete[$partner->salesId()] = $partner;
				$data['gCompetitors'][] = array("customerid" => $partner->partnerid(),
												"name1" => $partner->customer()->name1);

			break;

		}
	}
	$data['gItems'] = $root;
}
catch (Fox\Object\Exception\NotExist $e)
{
	Xview::instance()->systemError(Msg(Fox::MSGCL,4));
}
if(!$inquiry->exists())
{
	Xview::instance()->systemError(Msg(Fox::MSGCL,4));
}
$screen = new Screen("eInquiry","update");

$tabPanel = new TabPanel("tpInquiry");

// Main Tab [Header Data | Item Data | ]
$wrapper = new Wrapper("wMain");
$blHeader = Xview::instance()->component("inquiry", "header");
$blHeader->item("status")->input(true);
$blHeader->item("status")->unsetOption(Inquiry::STATUS_NEW);
$statusLabel = $blHeader->item("status")->description($status);
$screen->mainTitle("Modifier une Offre [<span class=\"status-$status\"> $statusLabel </span>]");//@TODO translate
$blHeader->add(new Fox\Html\Input("inquiryid"))->hidden();
$wrapper->add($blHeader);
$blItems = Xview::instance()->component("inquiry", "items",array("status" => $status,"inquiryid" => $inquiry->getId()));
$wrapper->add($blItems);

// Tasks
foreach($inquiry->tasks() as $task)
{
	$intId = $task->taskid;
	$bTask = Xview::instance()->component("inquiry","tasks");
	$bTask->id($intId);
	$bTask->label($task->message());
	$taskData = $task->getData();
	$bTask->initialize($task->getData());
	foreach($bTask->items() as $item)
	{
		$uniqueId = $item->id()."__".$intId;
		$bTask->item($item->id())->id($uniqueId);
	}
	if(!empty($taskData['duedate']))
		$bTask->collapsed();
	$tasksBlocks[$intId] = $bTask;
	$wrapper->add($bTask);
}

// Final Part
$blFinal = Xview::instance()->component("inquiry", "final",array("status" => $status,"inquiryid" => $inquiry->getId()));
$wrFinal = new Wrapper("bWFinal");
$wrFinal->add($blFinal);
$wrapper->add($wrFinal);
$tabPanel->add(new Tab("tMain",$blHeader->label,$wrapper));

// Customer Tab [Customer Data | ]
$blCustomer = Xview::instance()->component("inquiry", "customer");
$tabPanel->add(new Tab("tCustomer",$blCustomer->label,$blCustomer));

// Responsible Tab [Responsible Data | ]
$blResponsible = Xview::instance()->component("inquiry", "responsible",array("agency" => $data['agency']));
$tabPanel->add(new Tab("tResponsible",$blResponsible->label,$blResponsible));

// Competitor Tab [Responsible Data | ]
$blCompetitors = Xview::instance()->component("inquiry", "competitors");
$label = $blCompetitors->label;
if(count($data['gCompetitors']) > 0)
{
	$label .= " (".count($data['gCompetitors']).")";
}
$tabPanel->add(new Tab("tCompetitors",$label,$blCompetitors));
$screen->add($tabPanel);
$screen->initialize($data);

if($screen->submitted())
{
	$inquiryType = $blHeader->item("type")->get();
	// Make Optionnal Field Mandatory
	if(!empty($inquiryType) && ( $inquiryType == Inquiry::TYPE_PRIVATE
							  || $inquiryType == Inquiry::TYPE_LIMITATED) )
	{
		$blCustomer->item("street")->mandatory();
		$blCustomer->item("postal_code")->mandatory();
		$blCustomer->item("city")->mandatory();
		$blCustomer->item("phone1")->mandatory();
		$blCustomer->item("email1")->mandatory();
		if($status == Inquiry::STATUS_WIN)
		{
			$elm = $blFinal->item("contract_sedate");
			if(is_object($elm))
			{
				$blFinal->item("contract_sedate")->mandatory();
			}
		}
	}

	$inputs = $screen->get();
	if(!$screen->errors())
	{
		// Check Unicity of the Reference
		$finder = new Inquiry();
		$res = $finder->find(new SqlFragment("reference = ? AND inquiryid != ? ",
								array($inputs['reference'],$id)));
		if(count($res) > 0)
		{
			Message::Error(Msg(Sales::BUNDLE_NAME,Sales::MSG_DUPLICATE_INQUIRY,$inputs['reference']));
		}
	}
	if(count($inputs['gItems']) == 0)
	{
		Fox\Message::Error(Msg(Sales::BUNDLE_NAME,22));
	}
	else
	{
		$finalAmount = $inputs['amount_revised'] = $total = 0;
		$root = new Fox\Node(Fox\Node::ROOT_NODE);
		foreach($inputs['gItems'] as $line)
		{
			if(!isset($line['materialid']))
				continue;

			if(isset($treeData[$line['parentid']]))
			{
				$treeData[$line['parentid']]->setProperty("amount_revised",0);
				$treeData[$line['materialid']] = $treeData[$line['parentid']]->add(new Fox\Node($line));
			}
			else
			{
				$treeData[$line['materialid']] = $root->add(new Fox\Node($line));
			}

			if(isset($items[$line['materialid']]))
			{
				unset($items[$line['materialid']]);
			}

			// Build Items
			$item = new Inquiry\Item();
			$item->setFields($line);
			$inquiry->item($item);
			$total += $line['amount_initial'];
			// Pick Node without total
			if(empty($line['amount_initial']))
			{
				$nodeToBeChecked[] = $treeData[$line['materialid']];
			}
			$inputs['amount_revised'] += $line['amount_revised'];
			if(isset($line['amount']))
				$finalAmount += $line['amount'];
		}
		$blItems->item("gItems")->initialize($root,true);
		if($total == 0)
		{
			Fox\Message::Error(Msg(Sales::BUNDLE_NAME,23));
		}
		if($inputs['amount_revised'] > 0)
		{
			$blHeader->item("date_revision")->mandatory();
			$blHeader->item("date_revision")->get();
		}
		else
		{
			// Check that revision is empty
			if(!empty($inputs['date_revision']))
			{
				Message::Error(Msg(Messages::BUNDLE,Messages::ERR_TRANSMISSION_DATE_WITHOUT_REVISED_AMOUNTS));
			}
		}

		if($status == Inquiry::STATUS_WIN && $finalAmount == 0)
		{
			Fox\Message::Error(Msg(Fox\Message::BUNDLE_ERRORS,'4',$blItems->item("gItems")->fieldcat()->field("amount")->label()));
		}

		if(isset($nodeToBeChecked))
		{
			foreach($nodeToBeChecked as $node)
			{
				/* @var $node Fox\Node */
				if($node->getChildrenCount() > 0)
				{
					continue;
				}
				else
				{
					Fox\Message::Error(Msg(Sales::BUNDLE_NAME,93,$node->getProperty("label")));
				}
			}
		}

	}

	// Check Task
	foreach($inquiry->tasks() as $task)
	{

		$intData = array();
		$intId = $task->taskid;
		$dataTmp = $tasksBlocks[$intId]->get();
		foreach($dataTmp as $fieldName => $value)
		{
			$fieldRealName = preg_split("/__/",$fieldName);
			$intData[$fieldRealName[0]] = $value;
			if(!empty($intData['duedate']))
			{
				$tasksBlocks[$intId]->item("comment")->mandatory();
				$tasksBlocks[$intId]->item("comment")->get();// To Throw the issue
				$tasksBlocks[$intId]->collapsed(false);
			}

		}
		$task->setFields($intData);
		$inquiry->task($task);
	}

	if(!$screen->errors())
	{

		$customerData = $blCustomer->get();
		unset($customerData['customerid']);
		$contactData = $customerData;
		$customerData['name1'] = $inputs['customername'];
		$contactData['name1'] = $inputs['contact'];
		$contactData['type'] = Fox\Common\Customer::TYPE_CONTACT;

		// Delete deleted items
		if(isset($items) && is_array($items))
		{
			foreach($items as $item)
			{
				$inquiry->removeItem($item);
			}
		}

		try {
			unset($inputs['inquiryid']);
			$inquiry->setFields($inputs);
			// Manage Customer
			$customer = new Customer($inputs['customerid']);
			$keyname = Fox\Utilities::cleanup($inputs['customername']);
			if($customer->exists())
			{
				if($customer->keyname != $keyname)
				{
					$customer = new Customer();
					$customer->setFields($customerData);
				}
			}
			// Check if the customer does not exist in the database
			if(!$customer->exists())
			{
				// Check if the same customer exist
				$finder = new Customer();
				$keyname = Fox\Utilities::cleanup($inputs['customername']);
				$res = $finder->find(new Fox\Dao\SqlFragment("keyname = ?",array($keyname)));
				if(count($res) > 0)
				{
					$customer = $res[0];
				}
			}
			// Manage Customer adress changes
			$contact = new Customer($inputs['contactid']);

			$keyname = Fox\Utilities::cleanup($inputs['contact']);
			if($contact->exists())
			{
				if($contact->keyname != $keyname)
				{
					$contact = new Customer();
					$contact->setFields($contactData);
				}
			}
			$contact->setFields($contactData);
			if(!$contact->exists() && $customer->exists())
			{
				// Need to check if this contact is not already in the
				// partners list of the customer
				$contact = $customer->isPartner($contact);
			}
			// Create the customer
			if(!$customer->exists())
			{
				$customer->setFields(array("type" => Customer::TYPE_PROSPECT));
				$customer->create();
			}
			// Create the contact
			if(!$contact->exists() && !empty($contactData['name1']))
			{
				$contact->create();
				$partner = new Fox\Common\Customer\Partner();
				$partnerData['role'] = Role::CONTACT_PERSON;
				$partnerData['partnerid'] = $contact->getId();
				$partnerData['defaultflag'] = 0;
				$partnerData['customerid'] = $customer->getId();
				$partner->setFields($partnerData);
				$customer->partner($partner);

			}
			$customer->prepareUpdate(Customer::CHANGE_SALES);
			$customer->update();

			// Add Competitors to the Inquiry
			$competitors = $blCompetitors->item("gCompetitors")->get(null,true);
			foreach($competitors as $competitor)
			{
				if(!isset($competitor['customerid']))
					continue;
				$salesId = Role::COMPETITOR.":".$competitor['customerid'];

				if(isset($partnersToDelete[$salesId]))
				{
					unset($partnersToDelete[$salesId]);
				}
				else
				{
					$partner = new Partner();
					$partner->role = Role::COMPETITOR;
					$partner->setFields(array("customerid" => $competitor['customerid'],
												"role" => Role::COMPETITOR,
												"itemid" => 0));
					$inquiry->partners($partner);
				}
			}
			$opEntities = $blResponsible->item("op_entity")->default;
			if(is_array($opEntities))
			{
				foreach($opEntities as $partnerid => $value)
				{
					$salesId = Role::OPERATIONAL_ENTITY.":".$partnerid;
					if(isset($partnersToDelete[$salesId]))
					{
						unset($partnersToDelete[$salesId]);
					}
					else
					{
						$partner = new Partner();
						$partner->role = Role::OPERATIONAL_ENTITY;
						$partner->setFields(array("customerid" => $partnerid,
													"role" => Role::OPERATIONAL_ENTITY,
													"itemid" => 0));
						$inquiry->partners($partner);
					}
				}
			}

			// Add Customer
			$inquiry->partnerByRole($customer,Role::SOLD_TO_PARTY);
			$inquiry->customerid = $customer->customerid;
			// Add contact
			if(isset($contact) && $contact->exists() && !empty($contactData['name1']))
			{
				$inquiry->partnerByRole($contact,Role::CONTACT_PERSON);
			}

			try {
				// Responsible Entity
				$inquiry->partnerByRole(new Customer($inputs['agency']),Role::RESPONSIBLE_AGENCY);
				// Responsible Person
				$inquiry->partnerByRole(new Customer($inputs['sourceid']),Role::RESPONSIBLE_PERSON);
				// Successful bidder
				if(!empty($inputs['winnerid']))
				{
					$inquiry->partnerByRole(new Customer($inputs['winnerid']),Role::SUCCESSFUL_BIDER);
				}

			}
			catch (Fox\Object\Exception\NotExist $e)
			{
				// Do nothing -> should not be possible
			}



			// Text Management
			if(isset($inputs["cancel_reason"]))
			{
				$text = $inquiry->texts(Text::ID_CANCEL_REASON);
				$text->setFields(array('textid' => Text::ID_CANCEL_REASON,
										'language' => Xview::instance()->language(),
										'auto' => Text::MANUAL,
										'comment' => $inputs["cancel_reason"]));
				$inquiry->text($text);
			}

			$inquiry->prepareUpdate(Inquiry::CHANGE_DEFAULT);
			$inquiry->update();
			// Delete Removed Partners
			foreach($partnersToDelete as $partner)
			{
				$partner->delete();
			}

			$id = $inquiry->getId();
			Fox\Message::Success(Msg(Sales::BUNDLE_NAME,25,$id));
			Xview::instance()->redirect("?mod=inquiry&act=update&inquiryid=$id");
		}
		catch(Fox\Object\Exception\Save $e)
		{
			var_dump($e);
			Fox\Core\Errors::pushMessage($e);
		}
		catch (Fox\Object\Exception\NotExist $e)
		{
			Fox\Message::Error($e->getMessage());
		}
		catch (Exception $e)
		{
			var_dump($e);
			Fox\Message::Error($e->getMessage());
		}
	}
}
if(Fox\Authorization\Manager::check(user::AUTH_VIEW_ALL))
{
	$screen->toolbar()
			->add(new Fox\Html\Button("delete",
					Generator::display("delete",
					Generator::url("inquiry",
									"delete",
									null,
									array("inquiryid" => $id)))))
					->color(Fox\Html\Button::COLOR_RED);
}
echo $screen->Display();